<?php

class RequestHandler
{
	public static $responseVoid = false;

	public static function execute( AbstractApplication $application )
	{
		self::startSession();

		$configure = $application->getContextLoader()->configure;

		if ( !self::domainAuth( $configure ) )
			throw( new InvalidDomainException() );


		$request = self::getRequest( $configure );

		$service = $request["service"];
		$context = new Context( $application );

		$context->params = self::parseParams( $configure );
		$context->initialize($request, $service);

		// Verifica si se ha especificado el nombre de
		// un servicio, de lo contrario usa el default.
		//
		if ( !isset($service) )
		{
			include( $configure->indexFile );

			die();
		}
		else {
			$context->silent = false;  // Lamada interna a servicio.
		}

		$return = Services::invoke($service, $context);

		self::$responseVoid = !$return;

		return(
			self::endSession()
		);
	}

	private function parseParams( $configure )
	{
		$param = array();

		foreach ( array_keys($_POST) as $key ) {
			if ( $key != $configure->PARAM_REQUEST ) {
				$param[$key] = $_POST[$key];
			}
		}

		foreach ( array_keys($_SESSION) as $key ) {
			if ( !isset( $param[$key] ) )
				$param[$key] = $_SESSION[$key];
		}

		return($param);
	}

	private function getRequest( $configure )
	{
		if ( $configure->REQUEST_METHOD == "get" )
		{
			$request  = $_GET[ $configure->PARAM_REQUEST ];
			$encoding = $_GET[ $configure->PARAM_ENCODING ];
		}
		else {
			$request  = $_POST[ $configure->PARAM_REQUEST ];
			$encoding = $_POST[ $configure->PARAM_ENCODING ];
		}

		if ( $encoding == "base64" ){
			$request = base64_decode( $request );
		}
		elseif ( $encoding == "url" ){
			$request = urldecode( $request );
			$request = stripcslashes( $request );
		}

		$reqObject = CoreLib::json_decode( $request, true );

		return( $reqObject );
	}

	private function startSession()
	{
		Session::start();
	}

	private function endSession()
	{
		$responseStr = ServiceResponse::close();

		Session::stop();

		return( $responseStr );
	}

	/**
	 * Autentificación de dominio. Evita hot linking y RFI.
	 */
	private static function domainAuth( $configure )
	{
		for( $i = 0; $i < count( $configure->allowedDomains ); $i++ )
		{
			if ( $configure->allowedDomains[$i] == $_SERVER['HTTP_HOST'] ) {
				return(true);
			}
		}

		return(false);
	}
}
?>
